<template>
  <Header @get-instance="getInstanceFromTopBar"/>
  <a-flex horizontal gap="small"  justify="center" align="center" style="margin-top: 110px;margin-left: 50px;margin-right: 50px">
    <div style="width: 70%; padding: 1rem">
      <div>
        <div style="text-align: left;margin-left: 70px;">
          <h2>{{video.title}}</h2>
          <a-flex horizontal gap="large">
            <a-space size="small" align="center">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-play-fill" viewBox="0 0 16 16">
                <path d="m11.596 8.697-6.363 3.692c-.54.313-1.233-.066-1.233-.697V4.308c0-.63.692-1.01 1.233-.696l6.363 3.692a.802.802 0 0 1 0 1.393z"/>
              </svg>
              <span>{{video.playCount}}</span>
            </a-space>
            <a-space size="small" align="center">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-calendar4-range" viewBox="0 0 16 16">
                <path d="M3.5 0a.5.5 0 0 1 .5.5V1h8V.5a.5.5 0 0 1 1 0V1h1a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3a2 2 0 0 1 2-2h1V.5a.5.5 0 0 1 .5-.5zM2 2a1 1 0 0 0-1 1v1h14V3a1 1 0 0 0-1-1H2zm13 3H1v9a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V5z"/>
                <path d="M9 7.5a.5.5 0 0 1 .5-.5H15v2H9.5a.5.5 0 0 1-.5-.5v-1zm-2 3v1a.5.5 0 0 1-.5.5H1v-2h5.5a.5.5 0 0 1 .5.5z"/>
              </svg>
              <span>{{video.publishTime}}</span>
            </a-space>
          </a-flex>
        </div>
        <ArtPlayer id="artplayer-app" @get-instance="getInstanceFromArt" :option="option" style="width: 850px; height: 510px; margin: 30px auto 0"/>
        <div style="text-align: left;margin-left: 70px;">
          <!--点赞评论区-->
          <a-space style="margin-left: 15px" :size="40">
            <a-statistic title="点赞" :value="video.likeCount">
              <template #suffix>
                <icon @click="handleLike">
                  <template #component>
                    <svg v-if="video.isLike===1" xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-hand-thumbs-up-fill" viewBox="0 0 16 16">
                      <path d="M6.956 1.745C7.021.81 7.908.087 8.864.325l.261.066c.463.116.874.456 1.012.965.22.816.533 2.511.062 4.51a9.84 9.84 0 0 1 .443-.051c.713-.065 1.669-.072 2.516.21.518.173.994.681 1.2 1.273.184.532.16 1.162-.234 1.733.058.119.103.242.138.363.077.27.113.567.113.856 0 .289-.036.586-.113.856-.039.135-.09.273-.16.404.169.387.107.819-.003 1.148a3.163 3.163 0 0 1-.488.901c.054.152.076.312.076.465 0 .305-.089.625-.253.912C13.1 15.522 12.437 16 11.5 16H8c-.605 0-1.07-.081-1.466-.218a4.82 4.82 0 0 1-.97-.484l-.048-.03c-.504-.307-.999-.609-2.068-.722C2.682 14.464 2 13.846 2 13V9c0-.85.685-1.432 1.357-1.615.849-.232 1.574-.787 2.132-1.41.56-.627.914-1.28 1.039-1.639.199-.575.356-1.539.428-2.59z"/>
                    </svg>
                    <svg v-if="video.isLike===0" xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-hand-thumbs-up" viewBox="0 0 16 16">
                      <path d="M8.864.046C7.908-.193 7.02.53 6.956 1.466c-.072 1.051-.23 2.016-.428 2.59-.125.36-.479 1.013-1.04 1.639-.557.623-1.282 1.178-2.131 1.41C2.685 7.288 2 7.87 2 8.72v4.001c0 .845.682 1.464 1.448 1.545 1.07.114 1.564.415 2.068.723l.048.03c.272.165.578.348.97.484.397.136.861.217 1.466.217h3.5c.937 0 1.599-.477 1.934-1.064a1.86 1.86 0 0 0 .254-.912c0-.152-.023-.312-.077-.464.201-.263.38-.578.488-.901.11-.33.172-.762.004-1.149.069-.13.12-.269.159-.403.077-.27.113-.568.113-.857 0-.288-.036-.585-.113-.856a2.144 2.144 0 0 0-.138-.362 1.9 1.9 0 0 0 .234-1.734c-.206-.592-.682-1.1-1.2-1.272-.847-.282-1.803-.276-2.516-.211a9.84 9.84 0 0 0-.443.05 9.365 9.365 0 0 0-.062-4.509A1.38 1.38 0 0 0 9.125.111L8.864.046zM11.5 14.721H8c-.51 0-.863-.069-1.14-.164-.281-.097-.506-.228-.776-.393l-.04-.024c-.555-.339-1.198-.731-2.49-.868-.333-.036-.554-.29-.554-.55V8.72c0-.254.226-.543.62-.65 1.095-.3 1.977-.996 2.614-1.708.635-.71 1.064-1.475 1.238-1.978.243-.7.407-1.768.482-2.85.025-.362.36-.594.667-.518l.262.066c.16.04.258.143.288.255a8.34 8.34 0 0 1-.145 4.725.5.5 0 0 0 .595.644l.003-.001.014-.003.058-.014a8.908 8.908 0 0 1 1.036-.157c.663-.06 1.457-.054 2.11.164.175.058.45.3.57.65.107.308.087.67-.266 1.022l-.353.353.353.354c.043.043.105.141.154.315.048.167.075.37.075.581 0 .212-.027.414-.075.582-.05.174-.111.272-.154.315l-.353.353.353.354c.047.047.109.177.005.488a2.224 2.224 0 0 1-.505.805l-.353.353.353.354c.006.005.041.05.041.17a.866.866 0 0 1-.121.416c-.165.288-.503.56-1.066.56z"/>
                    </svg>
                  </template>
                </icon>
              </template>
            </a-statistic>
            <a-statistic title="收藏" :value="video.collectCount">
              <template #suffix>
                <icon :style="{ fontSize: '16px' }" @click="handleCollect">
                  <template #component>
                    <svg v-if="video.isCollect===0" xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16">
                      <path d="m8 2.748-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z"/>
                    </svg>
                    <svg v-if="video.isCollect===1" xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-heart-fill" viewBox="0 0 16 16">
                      <path fill-rule="evenodd" d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/>
                    </svg>
                  </template>
                </icon>
              </template>
            </a-statistic>
          </a-space>
          <a-divider />
          <p>{{video.videoIntroduce}}</p>
          <a-tag color="cyan">{{video.categoryName}}</a-tag>
          <a-divider />
          <a-typography-title :level="4">评论. {{video.commentCount}}</a-typography-title>
          <div>
            <a-comment>
              <template #avatar>
                <a-avatar :src="session.header" alt="Han Solo" />
              </template>
              <template #content>
                <a-form-item>
                  <a-textarea v-model:value="currentComment.contentOfVideo" show-count :maxlength="200" :rows="2" />
                </a-form-item>
                <a-form-item>
                  <a-button html-type="submit" :disabled="currentComment.contentOfVideo === ''" :loading="submitting" type="primary" @click="sendComment({model: 'video', fatherId: '', toCommentId: ''})">
                    发布
                  </a-button>
                </a-form-item>
              </template>
            </a-comment>
          </div>
          <div id="comment-list">
            <div>
              <a-anchor
                  direction="horizontal"
                  :affix="false"
                  :bounds="20"
                  @change="(link => {console.log(link)})"
                  :items="[
                    {
                      key: 'sort-hot',
                      href: '#sort-hot',
                      title: '热度',
                    },
                    {
                      key: 'sort-time',
                      href: '#sort-time',
                      title: '时间',
                    }
                ]"
              />
            </div>
            <a-comment v-for="(item, index) in commentList" :key="index">
              <template #actions>
                <!-- TODO 计算评论的喜欢数与讨厌数，并计算每条对于本用户是否喜欢 -->
                <span key="comment-basic-like">
                  <a-tooltip title="Like">
                    <template v-if="item.liked">
                      <LikeFilled @click="likeComment({level: 1, index: [index], isLike: item.liked})" />
                    </template>
                    <template v-else>
                      <LikeOutlined @click="likeComment({level: 1, index: [index], isLike: item.liked})" />
                    </template>
                  </a-tooltip>
                  <span style="padding-left: 8px; cursor: auto">
                    {{ item.beLikedCount }}
                  </span>
                </span>
                <span key="comment-basic-dislike">
                  <a-tooltip title="Dislike">
                    <template v-if="item.disliked">
                      <DislikeFilled @click="dislikeComment({level: 1, index: [index], isDislike: item.disliked})" />
                    </template>
                    <template v-else>
                      <DislikeOutlined @click="dislikeComment({level: 1, index: [index], isDislike: item.disliked})" />
                    </template>
                  </a-tooltip>
                  <span style="padding-left: 8px; cursor: auto">
                    {{ item.beDislikedCount }}
                  </span>
                </span>
                <span style="color: #aaaaaa" key="comment-nested-reply-to">
                  <a-space size="middle">
                    <svg v-if="item.userId !== session.userId"  @click="comment(item)" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-reply-fill" viewBox="0 0 16 16">
                      <path d="M5.921 11.9 1.353 8.62a.719.719 0 0 1 0-1.238L5.921 4.1A.716.716 0 0 1 7 4.719V6c1.5 0 6 0 7 8-2.5-4.5-7-4-7-4v1.281c0 .56-.606.898-1.079.62z"/>
                    </svg>
                  </a-space>
                </span>
              </template>
              <template #author>
                <a style="color: #aaaaaa">{{ item.userInfo.nickname }}</a>
              </template>
              <template #datetime>
                <a-tooltip>
                  <span>{{item.time}}</span>
                </a-tooltip>
              </template>
              <template #avatar>
                <a-popover title="个人资料" trigger="hover">
                  <template #content>
                    <a-flex vertical gap="small">
                      <a-space size="middle">
                        <a-avatar :src="item.userInfo.header" :size="55"/>
                        <a-flex vertical gap="small">
                          <div style="text-align: left">
                            <a-button type="link" size="large">{{ item.userInfo.nickname }}</a-button>
                          </div>
                          <div style="text-overflow: ellipsis;
                                          max-width: 300px;
                                          overflow: hidden;
                                          display: -webkit-box;
                                          -webkit-line-clamp: 2;
                                          text-align: left;
                                          -webkit-box-orient: vertical;">
                            {{ item.userInfo.introduce }}
                          </div>
                          <div>
                            <a-space wrap>
                              <a-button type="primary" @click="subscribe">
                                关注 {粉丝数}
                              </a-button>
                              <a-button type="primary" @click="sendMessage">
                                发私信
                              </a-button>
                            </a-space>
                          </div>
                        </a-flex>
                      </a-space>
                    </a-flex>
                  </template>
                  <a-avatar :src="item.userInfo.header" alt="Han Solo" />
                </a-popover>
              </template>
              <template #content>
                <p>
                  {{item.content}}
                </p>
                <div style="margin: 24px 0"  v-if="item.commentId === currentComment.commentId">
                  <a-textarea
                      show-count :maxlength="200"
                      v-model:value="currentComment.contentOfComment"
                      :placeholder="`@${item.userInfo.nickname}, 友好发表评论！最多200个字符`"
                      :auto-size="{ minRows: 2, maxRows: 5 }"
                  />
                  <a-button :loading="submitting" :disabled="currentComment.contentOfComment === ''" style="margin-top: 5px" type="primary" @click="sendComment({model: 'comment', fatherId: item.commentId, toCommentId: item.commentId})">发送</a-button>
                </div>
              </template>
              <a-comment v-for="(child, index2) in item.children" :key="index2">
                <template #actions>
                  <span key="comment-basic-like">
                  <a-tooltip title="Like">
                    <template v-if="child.liked">
                      <LikeFilled @click="likeComment({level: 2, index: [index, index2], isLike: child.liked})" />
                    </template>
                    <template v-else>
                      <LikeOutlined @click="likeComment({level: 2, index: [index, index2], isLike: child.liked})" />
                    </template>
                  </a-tooltip>
                  <span style="padding-left: 8px; cursor: auto">
                    {{ child.beLikedCount }}
                  </span>
                </span>
                  <span key="comment-basic-dislike">
                  <a-tooltip title="Dislike">
                    <template v-if="child.disliked">
                      <DislikeFilled @click="dislikeComment({level: 2, index: [index, index2], isDislike: child.disliked})" />
                    </template>
                    <template v-else>
                      <DislikeOutlined @click="dislikeComment({level: 2, index: [index, index2], isDislike: child.disliked})" />
                    </template>
                  </a-tooltip>
                  <span style="padding-left: 8px; cursor: auto">
                    {{ child.beDislikedCount }}
                  </span>
                </span>
                  <span style="color: #aaaaaa" @click="comment(child)">
                    <a-space size="middle">
                    <svg v-if="child.userId !== session.userId"  @click="comment(child)" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-reply-fill" viewBox="0 0 16 16">
                      <path d="M5.921 11.9 1.353 8.62a.719.719 0 0 1 0-1.238L5.921 4.1A.716.716 0 0 1 7 4.719V6c1.5 0 6 0 7 8-2.5-4.5-7-4-7-4v1.281c0 .56-.606.898-1.079.62z"/>
                    </svg>
                  </a-space>
                  </span>
                </template>
                <template #datetime>
                  <a-tooltip>
                    <span>{{child.time}}</span>
                  </a-tooltip>
                </template>
                <template #author>
                  <div v-if="child.toCommentId === item.commentId">
                    <a style="color: #aaaaaa">{{ child.userInfo.nickname }}</a>
                  </div>
                  <div v-else>
                    <a style="color: #aaaaaa">{{ child.userInfo.nickname }}</a>
                    <span style="color: #aaaaaa"> 回复 </span>
                    <a style="color: #aaaaaa">@{{ child.toUserInfo.nickname }}</a>
                  </div>
                </template>
                <template #avatar>
                  <a-popover title="个人资料" trigger="hover">
                    <template #content>
                      <a-flex vertical gap="small">
                        <a-space size="middle">
                          <a-avatar :src="child.userInfo.header" :size="55"/>
                          <a-flex vertical gap="small">
                            <div style="text-align: left">
                              <a-button type="link" size="large">{{ child.userInfo.nickname }}</a-button>
                            </div>
                            <div style="text-overflow: ellipsis;
                                          max-width: 300px;
                                          overflow: hidden;
                                          display: -webkit-box;
                                          -webkit-line-clamp: 2;
                                          text-align: left;
                                          -webkit-box-orient: vertical;">
                              {{ child.userInfo.introduce }}
                            </div>
                            <div>
                              <a-space wrap>
                                <a-button type="primary" @click="subscribe">
                                  关注 {粉丝数}
                                </a-button>
                                <a-button type="primary" @click="sendMessage">
                                  发私信
                                </a-button>
                              </a-space>
                            </div>
                          </a-flex>
                        </a-space>
                      </a-flex>
                    </template>
                    <a-avatar :src="child.userInfo.header" alt="Han Solo" />
                  </a-popover>
                </template>
                <template #content>
                  <p>
                    {{child.content}}
                  </p>
                  <div style="margin: 24px 0"  v-if="child.commentId === currentComment.commentId">
                    <a-textarea
                        show-count :maxlength="200"
                        v-model:value="currentComment.contentOfComment"
                        :placeholder="`@${child.userInfo.nickname}, 友好发表评论！最多200个字符`"
                        :auto-size="{ minRows: 2, maxRows: 5 }"
                    />
                    <a-button :loading="submitting" :disabled="currentComment.contentOfComment === ''" style="margin-top: 5px" type="primary" @click="sendComment({model: 'comment', fatherId: item.commentId, toCommentId: child.commentId})">发送</a-button>
                  </div>
                </template>
              </a-comment>
            </a-comment>
            <a-skeleton active v-if="commentOnLoading"/>
            <div v-if="currentCommentTotal >= video.commentCount">
              <h1>没有更多了！</h1>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div style="width: 30%; padding: 1rem">
      <div style="top: 130px; position: absolute">
        <a-flex vertical gap="large">
          <a-space size="middle">
            <a-avatar :src="video.header" :size="75"/>
            <a-flex vertical gap="small">
              <div style="text-align: left">
                <a-button type="link" size="large">{{video.nickname}}</a-button>
                <a-tooltip placement="top">
                  <template #title>
                    <span>发个私信</span>
                  </template>
                  <MessageOutlined :style="{ fontSize: '16px' }" @click="sendMessage"/>
                </a-tooltip>
              </div>
              <div style="text-overflow: ellipsis;
                        max-width: 300px;
                        overflow: hidden;
                        display: -webkit-box;
                        -webkit-line-clamp: 2;
                        text-align: left;
                        -webkit-box-orient: vertical;">
                这里放简介这里放简介这里放简介这里放简介这里放简介这里放简介
              </div>
              <div style="text-align: left">
                <a-space wrap>
                  <a-button type="primary" @click="subscribe">
                    关注 {粉丝数}
                  </a-button>
                </a-space>
              </div>
            </a-flex>
          </a-space>
          <div>这里放一些同类视频推荐</div>
        </a-flex>
      </div>
    </div>
  </a-flex>
</template>

<script setup>
import {ref, watch, onBeforeUnmount, createVNode, onMounted, reactive} from 'vue';
import router from "@/router/index.js";
import Header from "@/components/common/TopBar.vue";
import ArtPlayer from '@/components/common/ArtPlayer.vue';
import {formatISODate} from '@/utils/timeUtil.js'
import Icon, {MessageOutlined, ExclamationCircleOutlined,
  LikeOutlined, DislikeFilled, DislikeOutlined, LikeFilled } from "@ant-design/icons-vue";
import {message, Modal} from "ant-design-vue";
import {handleLikeRequest, handlePlayCount} from "@/api/VideoRequest.js";
import {sendCommentReq, loadCommentReq, likeDisLikeReq} from "@/api/CommentRequest.js";
import Pubsub from "pubsub-js";

const option = ref({
  id: router.currentRoute.value.params.videoId,
});
const video = ref({});
/** 评论最多两级, 一级评论的 toUserId为空 */
const commentList = ref([]);
// 当前评论对象的comment
const currentComment = ref({
  type: 1,
  targetId: '',
  fatherId: null, // 父评论的commentId
  toCommentId: null, // 评论其它评论的commentId
  contentOfVideo: '', //评论视频的评论
  contentOfComment: '', // 评论评论的评论
});

const session = ref({})
const submitting = ref(false);
const commentOnLoading = ref(false);
let currentCommentPage = 1;
let currentCommentTotal = 0;  // 当前已经加载的评论的总数
const sort = ref("#sort-time");
let artPlayer = null;
let playToken = '';
let isEnded = false;

const notLoginSign = Pubsub.subscribe('not-login', (msg, data) => {
  Modal.confirm({
    title: '你想发弹幕?',
    icon: createVNode(ExclamationCircleOutlined),
    content: '先去登录吧！',
    onOk() {
      return new Promise((resolve, reject) => {
        router.push('/login');
        resolve();
      }).catch(() => console.log('Oops errors!'));
    },
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    onCancel() {},
  });
});

const scroll = Pubsub.subscribe('scroll', (msg, data) => {
  if(!commentOnLoading.value) {
    loadComment();
  }
});

function initCurrentComment() {
  currentComment.value.fatherId = '';
  currentComment.value.toCommentId = '';
  currentComment.value.contentOfVideo = '';
  currentComment.value.contentOfComment = '';
}

//播放器播放次数
let playCount = 0;

function getInstanceFromArt(instance) {
  if(instance.code === 0){
    if (instance.data.video !== null) {
      video.value = instance.data.video;
      video.value.publishTime = formatISODate(new Date(video.value.publishTime));
      currentComment.value.targetId = video.value.videoId;
      artPlayer = instance.data.art_player;

      artPlayer.on('ready', () => {
        handlePlayCount(video.value.videoId, 1, '').then(res => {
          if(res.code === 0) {
            playToken = res.data;
          } else {
            message.error(res.msg);
          }
        })
      });

      artPlayer.on('play', () => {
        if(!isEnded) {
          playCount++;
          let type = 0;
          if(playCount === 1) {
            type = 2;
          } else {
            type = 3;
          }

          handlePlayCount(video.value.videoId, type, playToken).then(res => {
            if(res.code !== 0) {
              message.error(res.msg);
            }
          });
        }
      });

      artPlayer.on('pause', () => {
        if(!isEnded) {
          handlePlayCount(video.value.videoId, 4, playToken).then(res => {
            if(res.code !== 0) {
              message.error(res.msg);
            }
          });
        }

      });

      artPlayer.on('video:ended', () => {
        isEnded = true;
        handlePlayCount(video.value.videoId, 5, playToken).then(res => {
          if(res.code !== 0) {
            message.error(res.msg);
          }
        });
      });

      loadComment();
    } else {
      message.warn('视频不存在');
    }
  } else {
    message.error(instance.msg);
  }
}

function sendMessage() {
  console.log('私信');
}

function subscribe() {
  console.log('关注');
}

/**
 * 评论区评论评论，使评论框显现
 * @param toComment
 */
function comment(toComment) {
  currentComment.value.commentId = toComment ? toComment.commentId : '';
}

/**
 * 发送评论请求
 */
async function sendComment(data) {
  console.log('发送评论', data);
  submitting.value = true;
  currentComment.value.fatherId = data.fatherId;
  currentComment.value.toCommentId = data.toCommentId;
  const content = data.model === 'video' ? currentComment.value.contentOfVideo : currentComment.value.contentOfComment;
  const time = new Date();
  sendCommentReq(currentComment.value.type, currentComment.value.targetId,
      currentComment.value.fatherId, currentComment.value.toCommentId, content, time).then(res => {
        if(res.code !== 0) {
          message.error(res.msg);
        }  else {
          message.success('评论成功');
          currentComment.value.commentId = '';

          let comment = {
            commentId: res.data.commentId,
            targetId: video.value.videoId,
            fatherId: data.fatherId,
            userId: session.value.userId,
            userInfo: {
              userId: session.value.userId,
              nickname: session.value.nickname,
              header: session.value.header,
              introduce: session.value.introduce
            },
            toCommentId: data.toCommentId,
            content: content,
            time: formatISODate(time.toISOString()),
            beLikedCount: 0,
            beDislikedCount: 0,
            children: []
          };
          if(data.fatherId === '') {
            // 直接插入到一级评论
            commentList.value.unshift(comment);
          } else {
            // 插入二级评论
            //评论二级评论
            if (data.fatherId !== data.toCommentId) {
              comment['toUserInfo'] = {
                userId: res.data.toUserInfo.userId,
                nickname: res.data.toUserInfo.nickname,
                header: res.data.toUserInfo.header,
                introduce: res.data.toUserInfo.introduce
              }
            }

            for (let i = 0; i < commentList.value.length; i++) {
              if (commentList.value[i].commentId === data.fatherId) {
                commentList.value[i].children.unshift(comment);
                break;
              }
            }
          }
        }
        submitting.value = false;
        initCurrentComment();
  });

  // TODO 向对应的用户发起ws消息
}

/**
 * 视频点赞
 */
function handleLike() {
  handleLikeRequest(video.value.videoId).then(res => {
    if (res.code === 0) {
      video.value.isLike = res.data;
      video.value.likeCount = res.data === 1 ?
          video.value.likeCount + 1 : video.value.likeCount - 1;
    } else {
      message.warn(res.msg);
    }
  })
}

function getInstanceFromTopBar(instance) {
  session.value = instance.session;
}

function handleCollect() {
  console.log('收藏')
}

function loadComment() {
  if (currentCommentTotal < video.value.commentCount) {
    commentOnLoading.value = true;
    loadCommentReq(video.value.videoId, 1, 'time', currentCommentPage).then(res => {
      commentOnLoading.value = false;
      if (res.code === 0) {
        currentCommentPage++;
        res.data.forEach(level1 => {
          level1.time = formatISODate(new Date(level1.time));
          currentCommentTotal++;
          currentCommentTotal += level1.children.length;
          level1.children.forEach(level2 => {
            level2.time = formatISODate(new Date(level2.time));
          });
          commentList.value.push(level1);
        });
      } else {
        message.warn(res.msg);
      }
    })
  }
}

function likeComment(data) {
  const type = 1;
  let commentId = '';
  if(data.level === 1) {
    commentId = commentList.value[data.index[0]].commentId;
  }

  if(data.level === 2) {
    commentId = commentList.value[data.index[0]].children[data.index[1]].commentId;
  }

  likeDisLikeReq(commentId, type).then(res => {
    if (res.code === 0) {
      message.success('success');
      if(data.level === 1) {
        commentList.value[data.index[0]].liked = !commentList.value[data.index[0]].liked;
        if(data.isLike) {
          commentList.value[data.index[0]].beLikedCount--;
        } else {
          commentList.value[data.index[0]].beLikedCount++;
          commentList.value[data.index[0]].liked = true;
          if(commentList.value[data.index[0]].disliked) {
            commentList.value[data.index[0]].disliked = false;
            commentList.value[data.index[0]].beDislikedCount--;
          }
        }
      }

      if(data.level === 2) {
        commentList.value[data.index[0]].children[data.index[1]].liked = !commentList.value[data.index[0]].children[data.index[1]].liked
        if(data.isLike) {
          commentList.value[data.index[0]].children[data.index[1]].beLikedCount--;
        } else {
          commentList.value[data.index[0]].children[data.index[1]].beLikedCount++;
          commentList.value[data.index[0]].children[data.index[1]].liked = true;
          if(commentList.value[data.index[0]].children[data.index[1]].disliked) {
            commentList.value[data.index[0]].children[data.index[1]].disliked = false;
            commentList.value[data.index[0]].children[data.index[1]].beDislikedCount--;
          }
        }
      }
    } else {
      message.warn(res.msg);
    }
  });
}

function dislikeComment(data) {
  const type = 2;
  let commentId = '';
  if(data.level === 1) {
    commentId = commentList.value[data.index[0]].commentId;
  }

  if(data.level === 2) {
    commentId = commentList.value[data.index[0]].children[data.index[1]].commentId;
  }

  likeDisLikeReq(commentId, type).then(res => {
    if (res.code === 0) {
      message.success('success');
      if(data.level === 1) {
        commentList.value[data.index[0]].disliked = !commentList.value[data.index[0]].disliked;
        if(data.isDislike) {
          commentList.value[data.index[0]].beDislikedCount--;
        } else {
          commentList.value[data.index[0]].beDislikedCount++;
          commentList.value[data.index[0]].disliked = true;
          if(commentList.value[data.index[0]].liked) {
            commentList.value[data.index[0]].liked = false;
            commentList.value[data.index[0]].beLikedCount--;
          }
        }
      }

      if(data.level === 2) {
        commentList.value[data.index[0]].children[data.index[1]].disliked = !commentList.value[data.index[0]].children[data.index[1]].disliked;
        if(data.isDislike) {
          commentList.value[data.index[0]].children[data.index[1]].beDislikedCount--;
        } else {
          commentList.value[data.index[0]].children[data.index[1]].beDislikedCount++;
          commentList.value[data.index[0]].children[data.index[1]].disliked = true;
          if(commentList.value[data.index[0]].children[data.index[1]].liked) {
            commentList.value[data.index[0]].children[data.index[1]].liked = false;
            commentList.value[data.index[0]].children[data.index[1]].beLikedCount--;
          }
        }
      }

    } else {
      message.warn(res.msg);
    }
  });
}

onMounted(_=>{
  localStorage.setItem("redirectPath", router.currentRoute.value.fullPath);
  //commentOnLoading.value = true;
})

onBeforeUnmount(_ => {
  Pubsub.unsubscribe(notLoginSign);
  Pubsub.unsubscribe(scroll);

  if(!isEnded && playToken !== '') {
    handlePlayCount(video.value.videoId, 5, playToken).then(res => {
      if(res.code !== 0) {
        message.error(res.msg);
      }
    });
  }
})

</script>

<style scoped>

</style>